import os
import sys
from flask import Flask, render_template, request, jsonify
from werkzeug.utils import secure_filename
import time

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

from new_2_Interpret_script_Main import main, Epoch_Cross_Transformer, Seq_Cross_Transformer_Network, Intra_modal_atten, Window_Embedding, PositionalEncoding, Cross_modal_atten, Feed_forward
import json
from ai.sync import sync_vivogpt

app = Flask(__name__)

# 获取app.py文件的绝对路径
basedir = os.path.abspath(os.path.dirname(__file__))

# 设置上传文件夹为app.py同级目录下的data文件夹
UPLOAD_FOLDER = os.path.join(basedir, 'data')

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 将source_path设置为全局变量
source_path = ""
# 添加上传时间全局变量
upload_time = "未设置"


# 登录页
@app.route('/')
def login():
    return render_template('login.html')


# 脑电监测页
@app.route('/eeg-record', methods=['GET', 'POST'])
def EEG_record():
    global source_path, upload_time  # 声明使用全局变量
    if request.method == 'POST':
        # 获取上传的文件
        file = request.files['file']
        # 如果文件存在且文件名不为空
        if file and file.filename != '':
            # 使用secure_filename确保文件名安全
            filename = secure_filename(file.filename)
            # 保存文件到指定的文件夹
            upload_folder = app.config['UPLOAD_FOLDER']
            # 确保上传目录存在
            os.makedirs(upload_folder, exist_ok=True)  # 新增：自动创建目录
            file_path = os.path.join(upload_folder, filename)
            file.save(file_path)
            ##########################################
            source_path = file_path
            # 设置上传时间为当前时间
            upload_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print(f"文件上传时间: {upload_time}")
            print(f"文件路径: {source_path}")
            # main(filename)
            ##########################################
            print(f'文件 {filename} 已保存到 {upload_folder}')
    # 如果是GET请求，返回上传表单
    return render_template('eeg-record.html')


@app.route('/patient')
def patient():
    return render_template('patient.html')


@app.route('/sleep-report')
def sleep_report():
    content = sync_vivogpt()
    return render_template('sleep-report.html', content=content, report_time=upload_time)


# 定义一个新的路由来提供 sleep_data.json 的内容
@app.route('/sleep-data')
def sleep_data():
    # 返回静态的睡眠数据
    data = [
        {"name": "N1期", "value": 48},    # 10%
        {"name": "N2期", "value": 240},   # 50%
        {"name": "N3期", "value": 96},    # 20%
        {"name": "REM期", "value": 96}    # 20%
    ]
    return jsonify(data)


@app.route('/depression-report')
def depression_report():
    return render_template('depression-report.html', report_time=upload_time)

##################################################################
@app.route('/generate_sleep_report', methods=['POST'])
def generate_sleep_report():
    global source_path  # 声明使用全局变量
    try:
        # 获取前端发送的时间节点
        data = request.json
        start_time = data.get('start_time')


        # 直接传递 source_path 给 main 函数
        main(source_path, start_time)
        
        # 添加时间戳参数防止浏览器缓存
        timestamp = int(time.time())
        
        # 返回成功响应
        return jsonify({
            'success': True,
            'message': '报告生成成功',
            'imagePath': f'/static/picture/picture_5.jpg?t={timestamp}'  # 添加时间戳参数
        })
    except Exception as e:
        # 返回错误响应
        print(f"Error: {str(e)}")  # 打印错误信息以便调试
        return jsonify({
            'success': False,
            'message': str(e)
        })
######################################################################

if __name__ == "__main__":
    # app.run(debug=True, host='0.0.0.0')
    app.run(debug=True)